package mo.offer_special;

import java.util.*;

public class L111 {

    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        Map<String, Integer> variables = new HashMap<>();
        int nvars = 0;
        int n = equations.size();
        for (int i = 0; i < n; i++) {
            if (!variables.containsKey(equations.get(i).get(0))) {
                variables.put(equations.get(i).get(0), nvars++);
            }
            if (!variables.containsKey(equations.get(i).get(1))) {
                variables.put(equations.get(i).get(1), nvars++);
            }
        }

        double[][] graph = new double[nvars][nvars];
        for (int i = 0; i < nvars; i++) {
            Arrays.fill(graph[i], -1);
        }
        for (int i = 0; i < n; i++) {
            int va = variables.get(equations.get(i).get(0));
            int vb = variables.get(equations.get(i).get(1));
            graph[va][vb] = values[i];
            graph[vb][va] = 1.0 / values[i];
        }

        for (int k = 0; k < nvars; k++) {
            for (int i = 0; i < nvars; i++) {
                for (int j = 0; j < nvars; j++) {
                    if (graph[i][k] > 0 && graph[k][j] > 0) {
                        graph[i][j] = graph[i][k] * graph[k][j];
                    }
                }
            }
        }

        int querySize = queries.size();
        double[] ret = new double[querySize];
        for (int i = 0; i < querySize; i++) {
            int ia = variables.getOrDefault(queries.get(i).get(0), -1);
            int ib = variables.getOrDefault(queries.get(i).get(1), -1);
            if (ia >= 0 && ib >= 0) {
                ret[i] = graph[ia][ib];
            } else {
                ret[i] = -1;
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        L111 test = new L111();
        System.out.println(Arrays.toString(
                test.calcEquation(Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("b", "c")),
                new double[]{2.0, 3.0},
                Collections.singletonList(Arrays.asList("a", "c")))
        ));
    }

}
